package com.gzsxy.sso.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gzsxy.sso.common.dto.response.MenuRsp;
import com.gzsxy.sso.core.dao.MenuMapper;
import com.gzsxy.sso.core.entity.Menu;
import com.gzsxy.sso.core.entity.Permission;
import com.gzsxy.sso.core.dao.PermissionMapper;
import com.gzsxy.sso.core.entity.UserRole;
import com.gzsxy.sso.core.model.SessionUser;
import com.gzsxy.sso.core.service.PermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzsxy.sso.core.utils.SessionUserUtil;
import com.gzsxy.sso.core.utils.TreeUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Wrapper;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *   角色菜单关系
 * </p>
 *
 * @author zxl
 * @since 2021-11-10
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {


    private final static Logger log = LoggerFactory.getLogger(PermissionServiceImpl.class);


    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuMapper menuMapper;


    @Override
    public List<Permission> findAllPermission() {
        return permissionMapper.findAllPermission();
    }

    /**
     * @description: 根据角色添加权限
     * @param
     * @return
     */
    @Override
    public void addPermissionByRole(String roleId, String menuIds) {
//        SessionUser sessionUser = SessionUserUtil.getSessionUser();
//        String[] menuId = menuIds.split(",");
//        for (String id : menuId) {
//            //1.查询该角色是否已有该权限
//            LambdaQueryWrapper<Permission> wrapper = Wrappers.lambdaQuery();
//            wrapper.eq(Permission::getRoleId,roleId);
//            wrapper.eq(Permission::getMenuId,id);
//            Permission permission1 = baseMapper.selectOne(wrapper);
//            if (permission1 !=null){
//                log.info("功能id为:{}的权限已存在该角色",id);
//                continue;
//            }
//            Permission permission = new Permission();
//            permission.setRoleId(roleId);
//            permission.setMenuId(id);
////            permission.setAddUser(sessionUser.getUserName());
////            permission.setUpdateUser(sessionUser.getUserName());
//            baseMapper.insert(permission);
//        }
        //将菜单id分割（多个菜单）
        List<String> menuIdList = Arrays.asList(menuIds.split(","))
                //去除空字符串
                .stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
        //查询角色下所有的菜单权限
        LambdaQueryWrapper<Permission> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Permission::getRoleId,roleId);
        List<Permission> permissions = baseMapper.selectList(wrapper);

        //2.第二种方式（性能提高）
        List<Permission> addList = new ArrayList<>();
        //获取原有角色列表转为map对象
        Map<String, Permission> map = permissions.stream().collect(Collectors.toMap(Permission::getMenuId, o -> o));

        if (CollectionUtils.isNotEmpty(menuIdList)){
            for (String menuId : menuIdList) {
                //原角色列表中存在当前传入的角色id
                if (map.containsKey(menuId)){
                    //删除map对象中存在的元素
                    map.remove(menuId);
                } else {
                    //获取当前用户
//                    SessionUser sessionUser = SessionUserUtil.getSessionUser();
                    Permission permission = new Permission();
                    permission.setRoleId(roleId);
                    permission.setMenuId(menuId);
//                    userRole.setAddUser(sessionUser.getUserName());
//                    userRole.setUpdateUser(sessionUser.getUserName());
                    addList.add(permission);
                }
            }
        }
        //获取需要删除的id集合
        List<String> deleteIdList = map.values().stream().map(Permission::getId).collect(Collectors.toList());
        //批量删除
        if (CollectionUtils.isNotEmpty(deleteIdList)){
            baseMapper.deleteBatchIds(deleteIdList);
        }
        //批量添加
        if (CollectionUtils.isNotEmpty(addList)){
            this.saveBatch(addList);
        }

    }



    /**
     * @description: 删除角色下的功能权限
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class) //添加事务配置 异常回滚
    @Override
    public List<MenuRsp> deletefunctionByRoles(String roleId, String menuId) {
        //1.通过菜单Id查询它的所有子菜单
//        Map<String, Object> map = new HashMap<>();
//        map.put("parent_id",menuId);
        LambdaQueryWrapper<Menu> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Menu::getParentId, menuId);
        List<Menu> menus = menuMapper.selectList(queryWrapper);

        //2.查询当前角色下的所有权限
        Map<String, Object> map1 = new HashMap<>();
        map1.put("role_id",roleId);
        List<Permission> permissions = permissionMapper.selectByMap(map1);

        List<Permission> perList = new ArrayList<>();
        //更新修改用户
//        SessionUser sessionUser = SessionUserUtil.getSessionUser();
        //获取当前权限菜单下的记录
        Optional<Permission> first = permissions.stream().filter(permission -> permission.getMenuId().equals(menuId)).findFirst();
        Permission permission1 = first.get();
//        permission1.setUpdateUser(sessionUser.getUserName());
        perList.add(permission1);
        //当前角色下的所有权限
        Map<String, Permission> map = permissions.stream().collect(Collectors.toMap(Permission::getMenuId, o -> o));
        //如果当前菜单权限下有子菜单权限
        if (CollectionUtils.isNotEmpty(menus)){
            for (Menu menu : menus) {
                //当前角色下的权限中含有当前需要删除权限id下的子权限
                if (map.containsKey(menu.getId())){
                    Permission permission = map.get(menu.getId());
//                    permission.setUpdateUser(sessionUser.getUserName());
                    perList.add(permission);
                }
            }
        }
        //批量删除
        if (CollectionUtils.isNotEmpty(perList)){
            synchronized (this){
                this.updateBatchById(perList);
                List<String> list = perList.stream().map(Permission::getId).collect(Collectors.toList());
                permissionMapper.deleteBatchIds(list);
            }
        }

//        List<String> menuIdList = new ArrayList<>();
//        menuIdList.add(menuId);
//        //查询出某个功能菜单下的所有子菜单id
//        if (menus != null){
//            menus.forEach(menu -> {
//                if (permissions != null){
//                    for (Permission permission : permissions) {
//                        if (permission.getMenuId().equals(menu.getId())){
//                            menuIdList.add(permission.getMenuId());
//                        }
//                    }
//                }
//            });
//        }
//        //删除该功能下的所有子功能
//        menuIdList.forEach(id->{
//            LambdaQueryWrapper<Permission> wrapper = Wrappers.lambdaQuery();
//            wrapper.eq(Permission::getRoleId,roleId);
//            wrapper.eq(Permission::getMenuId,id);
////            Map<String, Object> map2 = new HashMap<>();
////            map2.put("role_id",roleId);
////            map2.put("menu_id",id);
//            Permission permission = permissionMapper.selectOne(wrapper);
//            if (!ObjectUtils.isEmpty(permission)){
//                //更新修改用户
//                SessionUser sessionUser = SessionUserUtil.getSessionUser();
//                permission.setUpdateUser(sessionUser.getUserName());
//                permissionMapper.update(permission,wrapper);
//                //删除记录
//                permissionMapper.delete(wrapper);
//            } else {
//                log.warn("角色id{}和菜单id{}权限功能不存在",roleId,id);
//            }
//
//        });
        //查询当前角色已经删除过后的功能权限
        List<MenuRsp> list = menuMapper.getfunctionByRoles(roleId);
        //获取树结构  Comparator.comparing(MenuRsp::getOrderId).reversed() 按照List中对象的getOrderId属性降序
        return TreeUtil.build(list,Comparator.comparing(MenuRsp::getOrderId).reversed());
    }
}
